﻿
//////////////////////////////////////////////////////
//
//  This project makes use of Alex Gorbatchev's SyntaxHighlighter project
//      located at http://alexgorbatchev.com/SyntaxHighlighter/
//
//  NOTE: much of this code is to get around issues arising when injecting the script while in edit mode.
//          TODO: resolve issues with injecting syntax scripts while in edit mode
//          if this can be resolved, we can move everything into the ScriptLinkModule, and this will be much cleaner and faster!
//
//////////////////////////////////////////////////////


//NOTE: this has been tested in IE only; cross browser support may require some extra cases to find selection text.
function ApplyCodeBlock(langName) {

    //alert("applying code block for language: " + langName);

    if (langName == "defaultbutton") {
        return;
    }

    var selectedText = (document.all) ? document.selection.createRange() : document.getSelection();

    if (selectedText != null && selectedText.text != null && selectedText.text.length > 0) {
        wrapSelectionWithPreTags(langName, selectedText.text);
    }
}


// This function sets the current selection to the selected text, wrapped inside of a pre-tag that
//       Syntax Highlighting javascript will read and re-format
function wrapSelectionWithPreTags(langName, selectedTextStr) {
    var sel, range, node;

    var html = "<pre class='brush: " + langName + "'>" + selectedTextStr + "</pre>";

    if (typeof window.getSelection != "undefined") {
        // IE 9+ and other non-IE browsers
        sel = window.getSelection();

        // Test that the Selection object contains at least one Range
        if (sel.getRangeAt && sel.rangeCount) {
            // Get the first Range (only Firefox supports more than one)
            range = window.getSelection().getRangeAt(0);
            range.deleteContents();

            // Create a DocumentFragment to insert and populate it with HTML
            // Need to test for the existence of range.createContextualFragment
            // because it's non-standard and IE 9 does not support it
            if (range.createContextualFragment) {
                // Ideally IE10 should hit this, in addition to chrome/firefox, but i'm not sure...
                node = range.createContextualFragment(html);
            } else {
                // In IE 9 we need to use innerHTML of a temporary element
                var div = document.createElement("div"), child;
                div.innerHTML = html;
                node = document.createDocumentFragment();
                while ((child = div.firstChild)) {
                    //while (child == div.firstChild) {
                    node.appendChild(child);
                }
            }
            range.insertNode(node);
        }
    }
    ////// removed because we aren't supporting any non-compliant browsers for editing any more //////
    /*else if (document.selection && document.selection.type != "Control") {

        // IE 8 and below
        range = document.selection.createRange();
        range.pasteHTML(html);
    }*/
}

function allSyntaxScriptsLoaded() {
    SyntaxHighlighter.all();
}

function coreSyntaxScriptLoaded() {

    // now that we've loaded the required shCore.js file, load the scripts for each supported language

    AddJavascriptLink("http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js", false);
    AddJavascriptLink("http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js", false);
    AddJavascriptLink("http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js", false);
    AddJavascriptLink("http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js", false);
    AddJavascriptLink("http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js", false);
    AddJavascriptLink("http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js", false);
    AddJavascriptLink("http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js", false);
    AddJavascriptLink("http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPlain.js", false);
    AddJavascriptLink("http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPowerShell.js", false);
    AddJavascriptLink("http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js", false);
    AddJavascriptLink("http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js", false);
    AddJavascriptLink("http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js", false);
    AddJavascriptLink("http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js", true);

}

// dynamically injects style ref into header of current page
function AddStyleLink(styleUrl) {
    var coreCssRef = document.createElement("link");
    coreCssRef.setAttribute("rel", "stylesheet");
    coreCssRef.setAttribute("type", "text/css");
    coreCssRef.setAttribute("href", styleUrl);
    document.getElementsByTagName("head")[0].appendChild(coreCssRef);
}

// dynamically injects javascript link into header of current page
function AddJavascriptLink(scriptUrl, useCallback) {
    var headId = document.getElementsByTagName('head')[0];
    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    if (useCallback) {
        newScript.onload = allSyntaxScriptsLoaded;
    }
    newScript.src = scriptUrl;
    headId.appendChild(newScript);
}

function TryAndInjectRequiredStuff() {
    
    // TODO: integrate these checks in addition to checking the page url (there may be cases where we don't want to load the syntax highlighting scripts and styles outside of EditPost.aspx)
                  
    //var inDesignMode = "0";
    //if (document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode != null) {
    //    inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
    //}
    //var wikiInEditMode = "0";
    //if (document.forms[MSOWebPartPageFormName]._wikiPageMode != null) {
    //    wikiInEditMode = document.forms[MSOWebPartPageFormName]._wikiPageMode.value;
    //}

    if (window.location.pathname.indexOf("EditPost.aspx") !== -1 || window.location.pathname.indexOf("NewPost.aspx") !== -1) {
        // in edit mode, don't inject anything
        
    } else {

        AddStyleLink("http://alexgorbatchev.com/pub/sh/current/styles/shCore.css");
        AddStyleLink("http://alexgorbatchev.com/pub/sh/current/styles/shCoreDefault.css");

        // we inject the core file first, and wait for the callback before injecting optional language scripts
        var headId = document.getElementsByTagName('head')[0];
        var newScript = document.createElement('script');
        newScript.type = 'text/javascript';
        newScript.onload = coreSyntaxScriptLoaded;
        newScript.src = "http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js";
        headId.appendChild(newScript);
        
    }
}

TryAndInjectRequiredStuff();
